import { getToken, setToken, removeToken } from '@/utils/auth'
import { login as loginApi, getUserinfo as getUserinfoApi } from '@/api/user'
import router from '@/router'

const state = {
  token: getToken(),
  userId: localStorage.getItem('userId')
}
const mutations = {
  updataToken(state, token) {
    state.token = token
    setToken(token)
  },
  delToken(state) {
    state.token = null
    removeToken()
  }
  // updataUserinfo(state, payload) {
  //   state.userinfo = payload
  // }
}
const actions = {
  async  login(context, data) {
    // console.log('调用了登录接口', data)
    const res = await loginApi(data) // 返回值是promise实例
    console.log(res)
    state.userId = res.userId
    localStorage.setItem('userId', res.userId)
    context.commit('updataToken', res.token)
  },
  async getUserinfo({ state }) {
    const res = await getUserinfoApi(state.userId)
    console.log(res)
    // commit('updataUserinfo', res)
  },
  logout({ commit }) {
    commit('delToken')
    router.push('/login')
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
